const type = "message"  // follow  message
const APP_BASE_API = "http://192.168.50.90:9317"
const messageContext = "㊔师指导，一小时迅速提升写作认知，帮助您的孩子轻松突破写作难题。我们的课程由经验丰富的专业教师团队精心设计，确保每个孩子都能找到适合自己的写作方法，激发写作兴趣，提升写作能力。"+'\n现在，只需关注薇心攻鍾呺【思无忧课堂】，输入关键词“666”，即可free get我们的精彩课程！'
auto();
console.show();
console.setPosition(100, 200);
restartApp("小红书")

const nativeIP = getNetworkIp()
const userList = getXhsUsers()
log("总用户"+userList.length)



log('等待五秒');
var sum = 1;
for(let i = 1; i <= 5; i++){
    sum += i;
  	sleep(1000)
    log(i+"秒")
}

sleep(500)
//先判断是不是在首页
var home = id("com.xingin.xhs:id/index_home").className("android.view.ViewGroup");
if (home.exists()) {
  home.click()
  //点击搜索按钮
  var searchBt = className("android.widget.Button").id("com.xingin.xhs:id/search");
  searchBt.click();
}

for (i = 0; i < userList.length; i++) { 
  //搜索输入框
  var searchEt = id("com.xingin.xhs:id/mSearchToolBarEt").className("android.widget.EditText");
  searchEt.waitFor(); 
  searchEt.setText(userList[i].xhs_user_id);
  log("填写搜索输入框")
  //等待
  sleep(500);
  //搜索页搜索按钮
  var searchTBt = id("com.xingin.xhs:id/mSearchToolBarSearch").className("android.widget.Button");
  log("点击搜索按钮")
  searchTBt.click();
  
  //等待Tab出现
  text("用户").waitFor()
  var userTab = className("androidx.appcompat.app.ActionBar$Tab").find();
  //点击用户
  userTab.get(1).click();
  //等待
  sleep(500);
  //用户item
  
  if(!text("没有找到相关用户，换个词试试吧").exists()){
      //用户存在
    var user = className("android.widget.RelativeLayout");
    //等待用户搜索
    user.waitFor();
    sleep(6000);
 
    if(type === "follow"){
        follow(userList[i].xhs_user_id)
    }else{
        sendMessage(user,userList[i].xhs_user_id)
    }
 
  
  }else{
    log("用户不存在：" +userList[i].xhs_user_id)
  }

  sleep(500);

  //删除上一个搜索条件
  var delUserId = id("com.xingin.xhs:id/mSearchResultToolBarDelete").className("android.widget.ImageView");
  delUserId.waitFor();
  delUserId.click();
  log("删除上一个用户搜索条件")
  sleep(30000);
}
exit()



//关注
function follow(userId) {
    //点击关注
    var follow = id("com.xingin.xhs:id/mSearchUserTvFollow").className("android.widget.TextView");
    if(follow.text("关注").exists()){
      log("关注："+userId)
      id("com.xingin.xhs:id/mSearchUserTvFollow").className("android.widget.TextView").findOne().click();
    }else{
      log("已关注："+userId )
      if(follow.text("已关注").exists()){
        log("已关注true："+userId )
        // continue
      }
    }
}

//发送消息
function sendMessage(user,userId) {
    //  点击用户
    log("点击用户")
    user.findOne().click();
    //   跳转主页
    log("跳转主页")
    //点击私信
    var message = id("com.xingin.xhs:id/userHeadLayoutSecondBtn").className("android.widget.ImageView"); //没关注的私信按钮
    message.waitFor();
    if(message.desc("取消关注").exists()){
        //message 按钮为取消关注
        message = id("com.xingin.xhs:id/userHeadLayoutMainBtn").className("android.widget.Button").text("发消息");
    }else{
      message = id("com.xingin.xhs:id/userHeadLayoutSecondBtn").className("android.widget.ImageView");
    }
    message.click();
    log("点击私信")

    //跳转私信发消息
    var messageET = id("com.xingin.xhs:id/chatInputContentView").className("android.widget.EditText");
    messageET.waitFor();
    messageET.setText(messageContext);
    log("输入消息")
    //点击发送
    var setBT = id("chatPushView").className("android.widget.TextView")
    setBT.waitFor()
    setBT.click()
    //返回服务器结果
    var messageResult = id("com.xingin.xhs:id/chatContentView").className("android.widget.TextView");
    var messagePush = id("com.xingin.xhs:id/pushStatusView").className("android.widget.ImageView");
    messageResult.waitFor()
    if(messageResult.exists()){
        setXhsUserMessage(userId)
    }
    
    log("点击发送")
    //等待
    sleep(1000);

    //返回用户主页
    var messageBack = id("com.xingin.xhs:id/msgBackIv").className("android.widget.ImageView");
    messageBack.click();
    log("返回用户主页")

    //返回用户列表
    var userHomeBack = id("com.xingin.xhs:id/profileActionBarLeftView").className("android.widget.ImageView");
    userHomeBack.waitFor();
    userHomeBack.click();
    log("返回用户列表")
}




//返回服务端信息时间
function setXhsUserMessage(userId) {
    var res = http.post(APP_BASE_API+"/xhsUser/update_xhsUser", {
        "xhs_user_id": userId,
        "status":1
    });
    if(res.statusCode != 200){
        toast("请求失败: " + res.statusCode + " " + res.statusMessage+"重新请求");
        setXhsUserMessage(userId)
    }else{
        toast("返回服务端成功！");
        log("返回服务端成功！");
        return true
    } 
}


//获得小红书用户
function getXhsUsers() {
    var res = http.get(APP_BASE_API+"/xhsUser/get_xhsUser_appList");
    if(res.statusCode != 200){
        toast("请求失败: " + res.statusCode + " " + res.statusMessage);
    }else{
        var xhsUsers = res.body.json();
        log(xhsUsers.data.xhsUsers);
        toast("用户列表请求成功");
        return xhsUsers.data.xhsUsers
    } 
}


//重启小红书
function restartApp(appName) {
  let forcedStopStr = ["强行停止","结束", "停", "强"];
  let packageName = "com.xingin.xhs"; //获取应用包名 通过软件名
  sleep(1500);
  if (packageName) {
    app.openAppSetting(packageName); //进入应用设置信息
    text(appName).waitFor(); //等待查询到名字出现
    log("软件名称出现");
    sleep(1500);
    for (var i = 0; i < forcedStopStr.length; i++) {
      if (textContains(forcedStopStr[i]).exists()) {
        //判定关键字是否存在z
        log("关键词存在");
        sleep(500);
        let forcedStop = textContains(forcedStopStr[i]).findOne();
        forcedStop.click(); //点击强行停止
        // text("取消").waitFor(); //等待二次确认停止框的‘取消’出现
        sleep(2000);
        if( text("确定").exists()){
            text("确定").click(); //如果不起效，说明控件不支持点击，click(‘xxx’)这种是全屏找字，直接点击字的坐标来进行点击！可以查找控件坐标位子，直接点击这个坐标来点击1
            sleep(3000);
        }
       
      
        log("准备打开app");
        text("打开").click()
        log("打开app");
        break;
      }
      
    }
  }
}

//获得本机内网ip
function getNetworkIp(){
    importClass('java.net.Inet4Address');
    importClass('java.net.InetAddress');
    importClass('java.net.NetworkInterface');
    importClass('java.util.Enumeration');
    importClass('java.net.Inet6Address');
    //获取内网IP地址
    var hostIp = null;
    try{
        var nis = NetworkInterface.getNetworkInterfaces();
        var ia = null;
        while (nis.hasMoreElements()) {
            var ni = nis.nextElement();
            var ias = ni.getInetAddresses();
            while (ias.hasMoreElements()) {  
                ia = ias.nextElement();  
                if (ia instanceof Inet6Address) {
                    continue;
                }
                var ip = ia.getHostAddress();
                if (!"127.0.0.1".equals(ip)) {
                    hostIp = ia.getHostAddress();
                    break;
                }
            }
        }
    } catch (e) {
        log(e);
    }
    log(hostIp);
    return hostIp;
}
 
